﻿Imports System.Web.UI.WebControls

Namespace DotNetNuke.Modules.ActiveForums
    Partial Public Class af_grid
        Inherits ForumBase
#Region "Private Members"
        Private RowCount As Integer = 0
        Private dtResults As DataTable
        Private PageSize As Integer = 20
        Private RowIndex As Integer = 0
#End Region
#Region "Event Handlers"
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Dim SortDirection As String
            If Not Request.Params("afsort") Is Nothing Then
                SortDirection = Request.Params("afsort")
            Else
                SortDirection = "DESC"
            End If
            BindPosts(0, SortDirection)
        End Sub
        Private Sub drpTimeFrame_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles drpTimeFrame.SelectedIndexChanged
            Response.Redirect(NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=grid", "afgt=activetopics", "ts=" & Convert.ToInt32(drpTimeFrame.SelectedItem.Value)}))
        End Sub
#End Region
#Region "Private Methods"
        Private Sub BindPosts(Optional ByVal Column As Integer = 0, Optional ByVal Sort As String = "ASC")
            PageSize = MainSettings.PageSize
            If UserId > 0 Then
                PageSize = UserDefaultPageSize
            End If
            If PageSize < 5 Then
                PageSize = 10
            End If

            If PageId = 1 Then
                RowIndex = 0
            Else
                RowIndex = ((PageId * PageSize) - PageSize)
            End If
            Dim db As New Data.Common
            Dim ForumIds As String = String.Empty
            Dim fc As New ForumController
            ForumIds = fc.GetForumsForUser(ForumUser.UserRoles, PortalId, ModuleId, "CanRead")
            Dim sCrumb As String = "<a href=""" & Utilities.NavigateUrl(TabId, "", New String() {ParamKeys.ViewType & "=grid", "afgt=xxx"}) & """>yyyy</a>"
            sCrumb = sCrumb.Replace("xxx", "{0}").Replace("yyyy", "{1}")
            If Not Request.Params("afgt") Is Nothing Then
                Dim gview As String = Utilities.XSSFilter(Request.Params("afgt")).ToLowerInvariant
                Select Case gview
                    Case "notread"
                        If Not Me.UserId = -1 Then
                            lblHeader.Text = GetSharedResource("[RESX:NotRead]")
                            dtResults = db.UI_NotReadView(PortalId, ModuleId, UserId, RowIndex, PageSize, Sort, ForumIds).Tables(0)
                            If dtResults.Rows.Count > 0 Then
                                RowCount = CInt(dtResults.Rows(0).Item("RecordCount"))
                            End If
                            Dim ctl As ForumBase = CType(LoadControl("~/DesktopModules/ActiveForums/controls/af_markallread.ascx"), ForumBase)
                            ctl.ModuleConfiguration = Me.ModuleConfiguration
                            plhMarkRead.Controls.Add(ctl)
                        Else
                            Response.Redirect(NavigateUrl(TabId), True)
                        End If
                    Case "unanswered"
                        lblHeader.Text = GetSharedResource("[RESX:Unanswered]")
                        dtResults = db.UI_UnansweredView(PortalId, ModuleId, UserId, RowIndex, PageSize, Sort, ForumIds).Tables(0)
                        If dtResults.Rows.Count > 0 Then
                            RowCount = CInt(dtResults.Rows(0).Item("RecordCount"))
                        End If
                    Case "tags"
                        Dim tagId As Integer = -1
                        If Not Request.QueryString("aftg") Is Nothing AndAlso IsNumeric(Request.QueryString("aftg")) Then
                            tagId = Integer.Parse(Request.QueryString("aftg"))
                        End If
                        lblHeader.Text = GetSharedResource("[RESX:Tags]")
                        dtResults = db.UI_TagsView(PortalId, ModuleId, UserId, RowIndex, PageSize, Sort, ForumIds, tagId).Tables(0)
                        If dtResults.Rows.Count > 0 Then
                            RowCount = CInt(dtResults.Rows(0).Item("RecordCount"))
                        End If
                    Case "mytopics"
                        If Not Me.UserId = -1 Then
                            lblHeader.Text = GetSharedResource("[RESX:MyTopics]")
                            dtResults = DataProvider.Instance.UI_MyTopicsView(PortalId, ModuleId, UserId, RowIndex, PageSize, Sort, UserInfo.IsSuperUser).Tables(0)
                            If dtResults.Rows.Count > 0 Then
                                RowCount = CInt(dtResults.Rows(0).Item("RecordCount"))
                            End If
                        Else
                            Response.Redirect(NavigateUrl(TabId), True)
                        End If
                    Case "activetopics"
                        lblHeader.Text = GetSharedResource("[RESX:ActiveTopics]")
                        Dim timeFrame As Integer = 1440 '24hours
                        If Not UserLastAccess = Utilities.NullDate Then
                            timeFrame = CInt(DateDiff(DateInterval.Minute, UserLastAccess, Now()))
                            drpTimeFrame.Items.Insert(0, New ListItem(GetDate(UserLastAccess), timeFrame.ToString))
                        End If

                        If Not Request.Params("ts") Is Nothing Then
                            If IsNumeric(Request.Params("ts")) Then
                                timeFrame = CInt(Request.Params("ts"))
                                If timeFrame < 15 Or timeFrame > 80640 Then
                                    timeFrame = 1440
                                End If
                            End If
                        End If
                        drpTimeFrame.Visible = True
                        drpTimeFrame.SelectedIndex = drpTimeFrame.Items.IndexOf(drpTimeFrame.Items.FindByValue(timeFrame.ToString))
                        dtResults = db.UI_ActiveView(PortalId, ModuleId, UserId, RowIndex, PageSize, Sort, UserInfo.IsSuperUser, timeFrame, ForumIds).Tables(0)
                        If dtResults.Rows.Count > 0 Then
                            RowCount = CInt(dtResults.Rows(0).Item("RecordCount"))
                        End If

                    Case Else
                        Response.Redirect(NavigateUrl(TabId), True)
                End Select
                sCrumb = String.Format(sCrumb, gview, lblHeader.Text)
                If MainSettings.UseSkinBreadCrumb Then
                    Environment.UpdateBreadCrumb(Page.Controls, sCrumb)
                End If
                Environment.UpdateMeta(Me.BasePage, "[VALUE] - " & lblHeader.Text, "[VALUE]", "[VALUE]")
            End If
            Try
                rptPosts.DataSource = dtResults
                rptPosts.DataBind()
                BuildPager()
            Catch ex As Exception

            End Try
        End Sub
        Private Sub BuildPager()
            Dim intPages As Integer
            intPages = CType(System.Math.Ceiling(RowCount / PageSize), Integer)
            Pager1.PageCount = intPages
            Pager1.CurrentPage = PageId
            Pager1.TabID = TabId
            Pager1.ForumID = ForumId
            Pager1.PageText = Utilities.GetSharedResource("[RESX:Page]")
            Pager1.OfText = Utilities.GetSharedResource("[RESX:PageOf]")
            Pager1.View = "grid"
            ' If UseAjax Then
            'Pager1.PageMode = Forums.Controls.PagerNav.Mode.CallBack
            ' Else
            Pager1.PageMode = Modules.ActiveForums.Controls.PagerNav.Mode.Links
            ' End If
            If MainSettings.URLRewriteEnabled Then
                If Not String.IsNullOrEmpty(MainSettings.PrefixURLBase) Then
                    Pager1.BaseURL = "/" & MainSettings.PrefixURLBase
                End If
                If Not String.IsNullOrEmpty(MainSettings.PrefixURLOther) Then
                    Pager1.BaseURL &= "/" & MainSettings.PrefixURLOther
                End If
                Pager1.BaseURL &= "/" & Request.Params("afgt") & "/"
                Pager1.PageMode = Modules.ActiveForums.Controls.PagerNav.Mode.Links
            End If
            If Not Request.Params("afsort") Is Nothing Then
                Dim Params As String() = {"afgt=" & Request.Params("afgt"), "afsort=" & Request.Params("afsort"), "afcol=" & Request.Params("afcol")}
                Pager1.Params = Params
            ElseIf Not Request.Params("ts") Is Nothing Then
                Dim Params As String() = {"afgt=" & Request.Params("afgt"), "ts=" & Request.Params("ts")}
                Pager1.Params = Params
            Else
                Dim Params As String() = {"afgt=" & Request.Params("afgt")}
                Pager1.Params = Params
            End If
        End Sub
#End Region
#Region "Public Methods"
        Public Function GetIcon(ByVal IsRead As Boolean, ByVal Icon As String, Optional ByVal Pinned As Boolean = False, Optional ByVal Locked As Boolean = False) As String
            Dim myTheme As String = MainSettings.Theme
            If Icon = String.Empty Then

                If Pinned = True Then
                    Return "~/DesktopModules/ActiveForums/themes/" & myTheme & "/topic_pin.png"
                ElseIf Locked = True Then
                    Return "~/DesktopModules/ActiveForums/themes/" & myTheme & "/emoticons/lock.gif"
                Else
                    If IsRead = True Then
                        Return "~/DesktopModules/ActiveForums/themes/" & myTheme & "/emoticons/document.gif"
                    Else
                        Return "~/DesktopModules/ActiveForums/themes/" & myTheme & "/emoticons/document_new.gif"
                    End If

                End If
            Else
                Return "~/DesktopModules/ActiveForums/themes/" & myTheme & "/emoticons/" & Icon
            End If
        End Function
        Public Function GetLastPost(ByVal UserID As Integer, ByVal UserName As String, ByVal DateAdded As DateTime, ByVal LastPostID As Integer, Optional ByVal ParentPostID As Integer = 0, Optional ByVal Subject As String = "", Optional ByVal ForumID As Integer = 0, Optional ByVal ReplyCount As Integer = 1, Optional ByVal FirstName As String = "", Optional ByVal LastName As String = "", Optional ByVal DisplayName As String = "") As String
            Try
                Dim PostId As Integer = LastPostID
                Dim sb As New Text.StringBuilder
                If Not UserName = "" Then
                    sb.Append("<nobr> [RESX:BY] ")
                    If UserID = 0 Or UserID = -1 Then
                        sb.Append(UserName)
                    Else
                        Dim isMod As Boolean = False
                        If CurrentUserType = CurrentUserTypes.Admin Or CurrentUserType = CurrentUserTypes.ForumMod Or CurrentUserType = CurrentUserTypes.SuperUser Then
                            isMod = True
                        End If
                        sb.Append(UserProfiles.GetDisplayName(ModuleId, MainSettings.ProfileVisibility, isMod, UserID, MainSettings.UserNameDisplay, UserName, FirstName, LastName, DisplayName))
                    End If
                    sb.Append("</nobr><br />")
                End If

                sb.Append("<nobr>" & GetDate(DateAdded) & "</nobr><br />")
                Return sb.ToString
            Catch ex As Exception
                Return "&nbsp;"
            End Try

        End Function
        Public Function GetTopic(ByVal TopicUrl As String, ByVal ForumUrl As String, ByVal GroupUrl As String, ByVal ForumGroupId As Integer, ByVal ForumID As Integer, ByVal TopicId As Integer, ByVal Subject As String, ByVal UserID As Integer, ByVal Replies As Integer, ByVal ForumName As String, ByVal UserName As String, Optional ByVal FirstName As String = "", Optional ByVal LastName As String = "", Optional ByVal PostType As String = "", Optional ByVal DisplayName As String = "", Optional ByVal LastReplyRead As Integer = 0) As String
            Dim sPollImage As String = ""
            If PostType = "POLL" Then
                sPollImage = "<img src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/themes/" & MainSettings.Theme & "/poll.gif") & """ align=""absmiddle"" border=""0"" alt=""[RESX:Poll]"" />"
            End If
            Dim ctlUtils As New ControlUtils
            Dim sTopicURL As String = String.Empty
            sTopicURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, GroupUrl, ForumUrl, ForumGroupId, ForumID, TopicId, TopicUrl, -1, -1, String.Empty, 1, SocialGroupId)

            Dim sOut As String = String.Empty
            'Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=" & Views.Topic}
            sOut = "<a href=""" & sTopicURL & """>" & sPollImage & Subject & "</a>"
            If LastReplyRead > 0 And LastReplyRead > TopicId Then
                If sTopicURL.EndsWith("/") Then
                    sOut &= "<a href=""" & sTopicURL & "?" & ParamKeys.FirstNewPost & "=" & LastReplyRead & """ rel=""nofollow""><img src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/themes/" & MainSettings.Theme & "/miniarrow_down.png") & """ style=""vertical-align:middle;"" alt=""[RESX:JumpToLastRead]"" border=""0"" class=""afminiarrow"" /></a>"
                Else
                    sOut &= "<a href=""" & NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.FirstNewPost & "=" & LastReplyRead}) & """ rel=""nofollow""><img src=""" & Page.ResolveUrl("~/DesktopModules/ActiveForums/themes/" & MainSettings.Theme & "/miniarrow_down.png") & """ style=""vertical-align:middle;"" alt=""[RESX:JumpToLastRead]"" border=""0"" class=""afminiarrow"" /></a>"
                End If

            End If
            sOut &= "<br />"
            Dim sForumURL As String = String.Empty
            sForumURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, GroupUrl, ForumUrl, ForumGroupId, ForumID, -1, -1, String.Empty, 0, SocialGroupId)
            sOut &= "<span class=""afsmalltext"">[RESX:BY] " & GetDisplayName(UserName, UserID, FirstName, LastName, DisplayName) & " " & GetSharedResource("IN.Text") & " <a href=""" & sForumURL & """>" & ForumName & "</a></span>"
            sOut &= GetSubPages(TabId, ModuleId, Replies, ForumID, TopicId)
            Return sOut
        End Function
        Public Function GetDisplayName(ByVal Username As String, ByVal UserID As Integer, Optional ByVal FirstName As String = "", Optional ByVal LastName As String = "", Optional ByVal DisplayName As String = "") As String
            Return UserProfiles.GetDisplayName(ModuleId, MainSettings.ProfileVisibility, False, UserID, MainSettings.UserNameDisplay, Username, FirstName, LastName, DisplayName)
        End Function
        Public Function GetRowCSS(ByVal IsRead As Boolean) As String
            If IsRead = True Then
                Return "aftopicrow"
            Else
                Return "aftopicrownew"
            End If
        End Function
        Public Function GetRowAltCSS(ByVal IsRead As Boolean) As String
            If IsRead = True Then
                Return "aftopicrowalt"
            Else
                Return "aftopicrownewalt"
            End If
        End Function
        Private Function GetSubPages(ByVal TabID As Integer, ByVal ModuleID As Integer, ByVal Replies As Integer, ByVal ForumID As Integer, ByVal PostID As Integer) As String
            Dim i As Integer
            Dim sOut As String = ""

            If Replies + 1 > PageSize Then
                sOut = "&nbsp;<div class=""afpagermini"">[RESX:SubPages]&nbsp;"
                'Jump to pages
                Dim intPostPages As Integer
                intPostPages = CType(System.Math.Ceiling((Replies + 1) / PageSize), Integer)
                If intPostPages > 5 Then
                    For i = 1 To 5
                        If UseAjax Then
                            'afPageJump
                            'sOut &= "<span class=""afpagerminiitem"" onclick=""javascript:afPageJump(" & i & ");"">" & i & "</span>&nbsp;"
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageJumpId & "=" & i}
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        Else
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageId & "=" & i}
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        End If

                    Next
                    If intPostPages > 6 Then
                        sOut &= "...&nbsp;"
                    End If
                    If UseAjax Then
                        'sOut &= "<span class=""afpagerminiitem"" onclick=""javascript:afPageJump(" & intPostPages & ");"">" & intPostPages & "</span>&nbsp;"
                        Dim Params2 As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageJumpId & "=" & intPostPages}
                        sOut &= "<a href=""" & NavigateUrl(TabID, "", Params2) & """>" & intPostPages & "</a>&nbsp;"
                    Else
                        Dim Params2 As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageId & "=" & intPostPages}
                        sOut &= "<a href=""" & NavigateUrl(TabID, "", Params2) & """>" & intPostPages & "</a>&nbsp;"
                    End If


                Else
                    For i = 1 To intPostPages
                        If UseAjax Then
                            'sOut &= "<span class=""afpagerminiitem"" onclick=""javascript:afPageJump(" & i & ");"">" & i & "</span>&nbsp;"
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageJumpId & "=" & i}
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        Else
                            Dim Params As String() = {ParamKeys.ForumId & "=" & ForumID, ParamKeys.TopicId & "=" & PostID, ParamKeys.ViewType & "=" & Views.Topic, ParamKeys.PageId & "=" & i}
                            sOut &= "<a href=""" & NavigateUrl(TabID, "", Params) & """>" & i & "</a>&nbsp;"
                        End If

                    Next
                End If

                sOut &= "</div>"
            End If
            Return sOut
        End Function
#End Region


    End Class
End Namespace
